require('dotenv').config()
// 导入数据库操作模块
const db = require('../../db')
// 导入 bcryptjs 这个包
const bcrypt = require('bcryptjs')

// MARK 员工管理

// MARK GET / sys / user	获取员工列表
exports.getList = (req, res) => {
   const { page, pagesize, keyword, departmentId } = req.query
   console.log("GET / sys / user /req.query >>>", req.query)
   // 验证输入数据
   if (!page || !pagesize) {
      return res.status(400).json({ success: false, code: 10062, message: '分页参数不能为空' })
   }

   const pageNumber = parseInt(page, 10)
   const pageSize = parseInt(pagesize, 10)

   if (isNaN(pageNumber) || isNaN(pageSize) || pageNumber <= 0 || pageSize <= 0) {
      return res.status(400).json({ success: false, code: 10063, message: '分页参数必须是正整数' })
   }

   // 计算偏移量
   const offset = (pageNumber - 1) * pageSize

   // 构建查询条件
   let query = `
    SELECT 
        e.id,
        e.staffPhoto,
        e.mobile,
        e.username,
        e.formOfEmployment,
        e.workNumber,
        e.timeOfEntry,
        d.name AS departmentName
    FROM 
        employee e
    LEFT JOIN 
        department d ON e.departmentId = d.id
  `

   let countQuery = `
    SELECT 
        COUNT(*) AS total
    FROM 
        employee e
    LEFT JOIN 
        department d ON e.departmentId = d.id
  `

   const queryParams = []

   if (keyword) {
      query += ` WHERE (e.username LIKE ? OR e.mobile LIKE ?)`
      countQuery += ` WHERE (e.username LIKE ? OR e.mobile LIKE ?)`
      queryParams.push(`%${keyword}%`, `%${keyword}%`)
   }

   if (departmentId && departmentId !== '1') {
      if (queryParams.length > 0) {
         query += ` AND e.departmentId = ?`
         countQuery += ` AND e.departmentId = ?`
      } else {
         query += ` WHERE e.departmentId = ?`
         countQuery += ` WHERE e.departmentId = ?`
      }
      queryParams.push(departmentId)
   }

   query += ` LIMIT ?, ?`
   queryParams.push(offset, pageSize)

   // 查询员工列表
   db.query(query, queryParams, (err, results) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10064, message: '查询员工列表失败', error: err.message })
      }

      // 查询总记录数
      db.query(countQuery, queryParams.slice(0, -2), (err, countResult) => {
         if (err) {
            return res.status(500).json({ success: false, code: 10065, message: '查询总记录数失败', error: err.message })
         }

         const total = countResult[0].total

         // 格式化响应数据
         const data = {
            total: total,
            rows: results.map(row => ({
               id: row.id,
               staffPhoto: row.staffPhoto,
               mobile: row.mobile,
               username: row.username,
               formOfEmployment: row.formOfEmployment,
               workNumber: row.workNumber,
               departmentName: row.departmentName,
               timeOfEntry: row.timeOfEntry
            }))
         }

         res.json({
            success: true,
            code: 0,
            data: data,
            message: '查询员工列表成功'
         })
      })
   })
}
// MARK POST / sys / user	新增员工
exports.addNew = (req, res) => {
   const { correctionTime, departmentId, formOfEmployment, mobile, staffPhoto, timeOfEntry, username } = req.body

   // 格式化日期
   const formattedCorrectionTime = new Date(correctionTime).toISOString().split('T')[0]
   const formattedTimeOfEntry = new Date(timeOfEntry).toISOString().split('T')[0]

   // 查询当前最大的 id
   const getMaxIdQuery = 'SELECT MAX(id) AS maxId FROM employee'

   db.query(getMaxIdQuery, (err, maxIdResult) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10009, message: '查询最大ID失败', error: err.message })
      }

      // 获取当前最大的 id
      const maxId = maxIdResult[0].maxId || 0

      // 生成新的 id
      const newId = maxId + 1

      // 生成工号
      const workNumber = `YULIANG${String(newId).padStart(4, '0')}`

      // 插入员工信息
      const insertQuery = `
      INSERT INTO employee (id, correctionTime, departmentId, formOfEmployment, mobile, staffPhoto, timeOfEntry, username, workNumber)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `

      db.query(insertQuery, [newId, formattedCorrectionTime, departmentId, formOfEmployment, mobile, staffPhoto, formattedTimeOfEntry, username, workNumber], (err, result) => {
         if (err) {
            return res.status(500).json({ success: false, code: 10010, message: '新增员工失败', error: err.message })
         }

         // 插入工资表
         const insertSalaryQuery = 'INSERT INTO salary (userId) VALUES (?)'
         db.query(insertSalaryQuery, [newId], (err, salaryResult) => {
            if (err) {
               return res.status(500).json({ success: false, code: 10011, message: '创建工资记录失败', error: err.message })
            }

            // 插入考勤表
            const insertAttendanceQuery = 'INSERT INTO attendances (userId) VALUES (?)'
            db.query(insertAttendanceQuery, [newId], (err, attendanceResult) => {
               if (err) {
                  return res.status(500).json({ success: false, code: 10012, message: '创建考勤记录失败', error: err.message })
               }

               // 插入社保表
               const insertSocialSecurityQuery = 'INSERT INTO social_securitys (userId) VALUES (?)'
               db.query(insertSocialSecurityQuery, [newId], (err) => {
                  if (err) {
                     return res.status(500).json({ success: false, code: 10013, message: '创建社保记录失败', error: err.message })
                  }
                  res.json({
                     success: true,
                     code: 10000,
                     data: {
                        id: newId,
                        workNumber: workNumber
                     },
                     message: '新增员工成功'
                  })
               })
            })
         })
      })
   })
}
// MARK GET / sys / user / { id }	获取员工基本信息
exports.getById = (req, res) => {
   const { id } = req.params

   // 查询员工基本信息
   const employeeQuery = `
    SELECT 
        e.id,
        e.mobile,
        e.staffPhoto,
        e.username,
        e.workNumber,
        e.timeOfEntry,
        e.correctionTime,
        e.departmentId,
        e.formOfEmployment
    FROM 
        employee e
    WHERE 
        e.id = ?
  `

   db.query(employeeQuery, [id], (err, employeeResults) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10011, message: '查询员工信息失败', error: err.message })
      }

      if (employeeResults.length === 0) {
         return res.status(404).json({ success: false, code: 10012, message: '员工不存在' })
      }

      const employee = employeeResults[0]

      // 查询部门名称
      const departmentQuery = `
      SELECT 
          d.name AS departmentName
      FROM 
          department d
      WHERE 
          d.id = ?
    `

      db.query(departmentQuery, [employee.departmentId], (err, departmentResults) => {
         if (err) {
            return res.status(500).json({ success: false, code: 10013, message: '查询部门信息失败', error: err.message })
         }

         if (departmentResults.length === 0) {
            return res.status(404).json({ success: false, code: 10014, message: '部门不存在' })
         }

         const departmentName = departmentResults[0].departmentName

         // 查询角色信息
         const roleQuery = `
        SELECT 
            roleId
        FROM 
            employee
        WHERE 
            id = ?
      `

         db.query(roleQuery, [id], (err, roleResults) => {
            if (err) {
               return res.status(500).json({ success: false, code: 10015, message: '查询角色信息失败', error: err.message })
            }
            const roleId = roleResults[0].roleId
            // const roleIds = .map(role => role.roleId)

            // 格式化响应数据
            const data = {
               id: employee.id,
               mobile: employee.mobile,
               staffPhoto: employee.staffPhoto,
               username: employee.username,
               workNumber: employee.workNumber,
               timeOfEntry: employee.timeOfEntry,
               correctionTime: employee.correctionTime,
               departmentId: employee.departmentId,
               departmentName: departmentName,
               formOfEmployment: employee.formOfEmployment,
               roleIds: roleId
            }

            res.json({
               success: true,
               code: 10000,
               data: data,
               message: '获取用户基本信息成功'
            })
         })
      })
   })
}
// MARK PUT / sys / user / { id }	修改员工基本信息
exports.putById = (req, res) => {
   const { id } = req.params
   const { staffPhoto, mobile, username, timeOfEntry, workNumber, correctionTime, departmentId, formOfEmployment } = req.body
   // MARK 维护初始数据
   if (id >= 1 && id <= 7) {
      return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
   }
   // 验证输入数据
   if (!mobile || !username || !timeOfEntry || !workNumber || !correctionTime || !departmentId || !formOfEmployment) {
      return res.status(400).json({ success: false, code: 10016, message: '必要字段不能为空' })
   }

   // 格式化日期
   const formattedCorrectionTime = new Date(correctionTime).toISOString().split('T')[0]
   const formattedTimeOfEntry = new Date(timeOfEntry).toISOString().split('T')[0]

   // 更新员工信息
   const updateQuery = `
    UPDATE employee
    SET 
        staffPhoto = ?,
        mobile = ?,
        username = ?,
        timeOfEntry = ?,
        workNumber = ?,
        correctionTime = ?,
        departmentId = ?,
        formOfEmployment = ?
    WHERE 
        id = ?
  `

   db.query(updateQuery, [staffPhoto, mobile, username, formattedTimeOfEntry, workNumber, formattedCorrectionTime, departmentId, formOfEmployment, id], (err, result) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10017, message: '更新员工信息失败', error: err.message })
      }

      if (result.affectedRows === 0) {
         return res.status(404).json({ success: false, code: 10018, message: '员工不存在' })
      }

      res.json({
         success: true,
         code: 10000,
         data: { id: id.toString() },
         message: '更新员工信息成功'
      })
   })
}
// MARK DELETE / sys / user / { id }	删除员工
exports.delById = (req, res) => {
   const { id } = req.params

   // 验证输入数据
   if (!id) {
      return res.status(400).json({ success: false, code: 10019, message: '员工ID不能为空' })
   }
   // MARK 维护初始数据
   if (id >= 1 && id <= 7) {
      return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
   }
   // 删除关联表中的记录
   const deleteApprovalQuery = 'DELETE FROM approval WHERE userId = ?';
   const deleteSalaryQuery = 'DELETE FROM salary WHERE userId = ?';
   const deleteAttendancesQuery = 'DELETE FROM attendances WHERE userId = ?';
   const deleteSocialSecuritysQuery = 'DELETE FROM social_securitys WHERE userId = ?';

   // 删除员工信息
   const deleteEmployeeQuery = `
      DELETE FROM employee
      WHERE 
          id = ?
   `;

   // 执行删除操作
   db.query(deleteApprovalQuery, [id], (err) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10020, message: '删除员工信息失败', error: err.message });
      }

      db.query(deleteSalaryQuery, [id], (err) => {
         if (err) {
            return res.status(500).json({ success: false, code: 10020, message: '删除员工信息失败', error: err.message });
         }

         db.query(deleteAttendancesQuery, [id], (err) => {
            if (err) {
               return res.status(500).json({ success: false, code: 10020, message: '删除员工信息失败', error: err.message });
            }

            db.query(deleteSocialSecuritysQuery, [id], (err) => {
               if (err) {
                  return res.status(500).json({ success: false, code: 10020, message: '删除员工信息失败', error: err.message });
               }

               db.query(deleteEmployeeQuery, [id], (err, result) => {
                  if (err) {
                     return res.status(500).json({ success: false, code: 10020, message: '删除员工信息失败', error: err.message });
                  }

                  if (result.affectedRows === 0) {
                     return res.status(404).json({ success: false, code: 10021, message: '员工不存在' });
                  }

                  res.json({
                     success: true,
                     code: 10000,
                     data: null,
                     message: '删除员工信息成功'
                  });
               });
            });
         });
      });
   });
}
// MARK PUT / sys / user / assignRoles	分配员工角色
exports.setRole = (req, res) => {
   const { id, roleId } = req.body;

   // 验证输入数据
   if (!id) {
      return res.status(400).json({ success: false, code: 10066, message: '员工ID不能为空' });
   }
   // MARK 维护初始数据
   if (id >= 1 && id <= 7) {
      return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
   }
   if (!roleId) {
      return res.status(400).json({ success: false, code: 10072, message: '角色ID不能为空' });
   }

   // 更新员工角色
   const updateQuery = `
      UPDATE employee
      SET roleId = ?
      WHERE id = ?
   `;

   db.query(updateQuery, [roleId, id], (err, result) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10073, message: '更新员工角色失败', error: err.message });
      }

      if (result.affectedRows === 0) {
         return res.status(404).json({ success: false, code: 10074, message: '员工不存在' });
      }

      res.json({
         success: true,
         code: 10000,
         data: { id: id.toString() },
         message: '分配员工角色成功'
      });
   });
}
// MARK GET / sys / user / simple	获取员工简单列表
exports.getSimpleList = (req, res) => {
   // 查询 employee 表获取所有员工的 id 和 username
   const query = `
    SELECT 
        id,
        username
    FROM 
        employee
  `

   db.query(query, (err, results) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10008, message: '查询员工列表失败', error: err.message })
      }

      // 格式化响应数据
      const data = results.map(row => ({
         id: row.id, // 确保 id 是int
         username: row.username
      }))

      res.json({
         success: true,
         code: 10000,
         data: data,
         message: '获取员工列表成功'
      })
   })
}
// MARK 用户相关

// MARK PUT / sys / user / updatePass	修改用户密码
exports.updatePass = (req, res) => {
   const { oldPassword, newPassword } = req.body
   const userId = req.user.id // 在中间件中解析 JWT 并将用户信息存储在 req.user 中
   // MARK 维护初始数据
   if (id >= 1 && id <= 4) {
      return res.status(200).json({ success: false, code: 10023, message: '重要账号不可修改密码！' })
   }
   // 验证输入数据
   if (!oldPassword || !newPassword) {
      return res.status(400).json({ success: false, code: 10001, message: '旧密码和新密码不能为空' })
   }
   if (newPassword != '123456' || newPassword != '1234567') {
      return res.status(400).json({ success: false, code: 10001, message: '避免密码丢失，仅支持设置密码123456或1234567' })
   }
   // 查询用户信息
   const query = 'SELECT * FROM user WHERE id = ?'
   db.query(query, [userId], (err, results) => {
      if (err) {
         return res.status(500).json({ success: false, code: 10002, message: '查询用户失败', error: err.message })
      }
      if (results.length === 0) {
         return res.status(404).json({ success: false, code: 10003, message: '用户不存在' })
      }
      const user = results[0]
      // 验证旧密码
      bcrypt.compare(oldPassword, user.password, (err, isMatch) => {
         if (err) {
            return res.status(500).json({ success: false, code: 10004, message: '密码验证失败', error: err.message })
         }
         if (!isMatch) {
            return res.status(400).json({ success: false, code: 10005, message: '旧密码错误' })
         }
         // 加密新密码
         bcrypt.hash(newPassword, 10, (err, hashedPassword) => {
            if (err) {
               return res.status(500).json({ success: false, code: 10006, message: '加密新密码失败', error: err.message })
            }
            // 更新用户密码
            const updateQuery = 'UPDATE user SET password = ? WHERE id = ?'
            db.query(updateQuery, [hashedPassword, userId], (err, result) => {
               if (err) {
                  return res.status(500).json({ success: false, code: 10007, message: '更新密码失败', error: err.message })
               }
               res.json({
                  success: true,
                  code: 10000,
                  message: '密码更新成功'
               })
            })
         })
      })
   })
}
